#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QProcess>
#include <QDebug>
#include <QDomDocument>
#include <QDomElement>
#include <QDomNodeList>
#include <QDomAttr>
#include "BaiduHanDict.h"
#include "global.h"

QString BaiduHanDict::HanDict(QString keyWord)
{
    QByteArray html = getUrlRawContent("https://hanyu.baidu.com/s?wd=" + keyWord + "&ptype=zici");
    // parse html to xml
    QProcess tidy;
    QStringList args;
    args << "-q" << "-asxml" <<  "--show-warnings" << "no";
    tidy.start("tidy", args);
    tidy.waitForStarted();
    tidy.write(html);
    tidy.closeWriteChannel();
    tidy.waitForFinished(2000);
    QString xmlText;
    if (tidy.state() == QProcess::NotRunning && (tidy.exitCode() == 0 || tidy.exitCode() == 1))
        xmlText = tidy.readAllStandardOutput();
    else
    {
        qWarning() << "parse html to xml error";
        tidy.terminate();
    }

    QDomDocument doc;
    doc.setContent(xmlText);
    QDomNodeList divNodeList = doc.elementsByTagName("div");
    QString result;
    QString title;
    for (int i = 0; i < divNodeList.size(); ++i) {
        QDomElement domElement = divNodeList.at(i).toElement();
        QDomAttr idAttribute = domElement.attributeNode("id");
        QDomAttr classAttribute = domElement.attributeNode("class");
        QString text;


        if (classAttribute.value() == "poem-detail-header-info")
        {
            text = domElement.text();
            if (text.endsWith("译文对照"))
                text.remove("译文对照");
            if (!text.isEmpty())
            {
                result.prepend(text + "\n");
            }
        }

        if (idAttribute.value() == "pinyin")
        {
            result.prepend("拼音 " + domElement.text() + "\n");
        }
        else if (idAttribute.value() == "basicmean-wrapper")
        {
            text = innerText(domElement);
            if (!text.isEmpty())
            {
                result += "基本释义\n";
                result += text;
            }

        }
        else if (idAttribute.value() == "source-wrapper")
        {
            text = innerText(domElement);
            if (!text.isEmpty())
            {
                result += "出处\n";
                result += text;
            }
        }
        else if (idAttribute.value() == "poem-detail-header")
        {
            title = domElement.firstChildElement("h1").text();
            text = innerText(domElement, "poem-detail-main-text");
            if (!text.isEmpty())
            {
                // result += "内容\n";
                result += text;
            }

            text = innerText(domElement, "poem-detail-main-text body-means-p");
            if (!text.isEmpty())
            {
                result += "译文\n";
                result += text;
            }
        }
    }
    if (!title.isEmpty())
        result.prepend( QString("<big>%1</big>\n").arg(title));
    result.replace("\n", "<br/>");
    // qDebug() << result;


    return result;
}

BaiduHanDict::BaiduHanDict()
{
    manager = networkManagerInstance();
}

QByteArray BaiduHanDict::getUrlRawContent(QString url_str)
{
    QUrl url(url_str);
    QNetworkRequest req(url);
    req.setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) "
                                                    "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
    QNetworkReply *reply = manager->get(req);
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();
    if (reply->error() != QNetworkReply::NoError)
    {
        qWarning() << reply->errorString();
    }
    QByteArray res = reply->readAll();
    reply->deleteLater();
    return res;
}

QString BaiduHanDict::innerText(const QDomElement &domElement, QString classValue)
{
    QString text;
    // extract text from <p>
    QDomNodeList pNodeList = domElement.elementsByTagName("p");
    for (int i = 0; i < pNodeList.size(); ++i)
    {
        QDomElement pElement = pNodeList.at(i).toElement();
        if (classValue.isEmpty() || pElement.attributeNode("class").value() == classValue)
        {
            if (text.endsWith("\n") && pElement.text().startsWith("\n"))
                text.remove(text.length() - 1, 1);
            text += pElement.text();
        }
        if (!text.endsWith("\n"))
            text += "\n";
    }

    if (text.isEmpty())
    {
        // extract text from <div>
        QDomNodeList divNodeList = domElement.elementsByTagName("div");
        for (int i = 0; i < divNodeList.size(); ++i)
        {
            QDomElement divElement = divNodeList.at(i).toElement();
            if (classValue.isEmpty() || divElement.attributeNode("class").value() == classValue)
            {
                if (text.endsWith("\n") && divElement.text().startsWith("\n"))
                    text.remove(text.length() - 1, 1);
                text += divElement.text();
            }
            if (!text.endsWith("\n"))
                text += "\n";
        }
    }
    if (text.startsWith("\n"))
        text.remove(0, 1);

    return text;
}


